const router = require('koa-router')()
const app = require('../app')
const Leave = require("../models/leaveSchema")
const Dept = require("../models/deptSchema")
const utils = require("../utils/utils")

router.prefix('/leave')

router.get("/list", async (ctx) => {
  const { applyState } = ctx.request.query;
  let authorization = ctx.request.headers.authorization;
  let { data } = utils.decode(authorization);
  const { page, skipIndex } = utils.pager(ctx.request.query);

  let params = {
    "applyUser.userId": data.userId
  }

  if (applyState) params.applyState = applyState;

  const query = Leave.find(params);

  const list = await query.skip(skipIndex).limit(page.pageSize)
  const total = await Leave.countDocuments(params)

  ctx.body = utils.success({
    page: { ...page, total }, list
  })
})


router.post('/operate', async (ctx) => {
  const { _id, action, ...params } = ctx.request.body;
  let authorization = ctx.request.headers.authorization;
  let { data } = utils.decode(authorization);
  let res, info;

  try {
    if (action == "create") {
      let orderNo = "XJ";
      orderNo += utils.formateDate(new Date(), "yyyyMMdd")
      const total = await Leave.countDocuments();
      params.orderNo = orderNo + total;
      // 获取用户当前部门的id
      let id = data.deptId.pop();
      // 查找这个部门负责任的信息
      let dept = await Dept.findById(id);
      // 获取人事部门和财务部门的信息
      let userList = await Dept.find({ deptName: { $in: ['人事', '财务'] } });
      let auditUsers = dept.userName;//审批人的集合
      let curAuditUserName = dept.userName;//当前审批人
      let auditFlows = [
        {
          userId: dept.deptId,
          userName: dept.deptName,
          userEmail: dept.userEmail
        }
      ]
      userList.map(item => {
        auditFlows.push({
          userId: item.userId,
          userName: item.userName,
          userEmail: item.userEmail,
        })
        auditUsers += "," + item.userName;
      })

      params.auditUsers = auditUsers;
      params.curAuditUserName = curAuditUserName;
      params.auditFlows = auditFlows;
      params.auditLogs = [];
      params.applyUser = {
        userId: data.userId,
        userName: data.userName,
        userEmail: data.userEmail,
      };

      res = await Leave.create(params)
      info = "创建成功"
    } else if (action == "edit") {
      params.updateTime = new Date()
      res = await Dept.findByIdAndUpdate(_id, params)
      info = "编辑成功"
    } else {
      await Dept.findByIdAndRemove(_id)
      await Dept.deleteMany({
        parentId: {
          $all: [_id]
        }
      })
      info = "删除成功"
    }
    ctx.body = utils.success({}, info);
  } catch (error) {
    ctx.body = utils.fail({}, error.stack);

  }

})



module.exports = router
